package middleware

import (
	"api/internal/types"
	"fmt"
	"github.com/golangblogs/jwt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"strconv"
)

type AuthTokenMiddleware struct {
}

func NewAuthTokenMiddleware() *AuthTokenMiddleware {
	return &AuthTokenMiddleware{}
}

func (m *AuthTokenMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		fmt.Println("触发中间件")
		token := r.Header.Get("token")
		if token == "" {
			resp := types.Response{
				Code: 500,
				Msy:  "token不能为空",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
		j := jwt.NewJWT()
		parseToken, err := j.ParseToken(token)
		if err != nil {
			if jwt.TokenExpired == err {
				resp := types.Response{
					Code: 500,
					Msy:  "登录超时",
					Data: nil,
				}
				httpx.OkJsonCtx(r.Context(), w, resp)
			}
		}
		r.ParseForm()
		r.Form.Set("userId", strconv.Itoa(int(parseToken.ID)))
		// Passthrough to next handler if need
		next(w, r)
	}
}
